using UnityEngine;
using System.Collections;

public class GridMeshScript  {

	public static GameObject CreateGrid( Vector3 position,  Material material, int Vertical, int Horizontal,float scale )
	{
		GameObject gridObject = new GameObject( "Grid" + Vertical + Horizontal );
		gridObject.transform.position = position+Vector3.forward;
		
		MeshFilter m = gridObject.AddComponent<MeshFilter>() as MeshFilter;
		m.mesh = _getMesh();
		
		MeshRenderer mr = gridObject.AddComponent<MeshRenderer>();
		mr.castShadows = false;
		mr.receiveShadows = false;
		mr.material = material;
		
		gridObject.transform.localScale = new Vector3( scale, scale, 0 );
		return gridObject;
	}
	public static Mesh _getMesh()
	{
		if ( _plane )
			return _plane;
		_plane = new Mesh();
		
		_plane.name = "Grid Plane Mesh";
		
		Vector3[] verts = new Vector3[4];
        verts[0] = new Vector3(-.5f, -.5f, 0);
        verts[1] = new Vector3(.5f, -.5f, 0);
        verts[2] = new Vector3(-.5f, .5f, 0);
        verts[3] = new Vector3(.5f, .5f, 0);
		

		
		int[] tris = new int[]{ 2, 1, 0, 3, 1, 2 };
		
		Vector2[] uvs = new Vector2[verts.Length];

        uvs[0] = new Vector2(0, 1);
        uvs[1] = new Vector2(1, 1);
        uvs[2] = new Vector2(0, 0);
        uvs[3] = new Vector2(1, 0);
		
		_plane.vertices = verts;
        _plane.triangles = tris;
        _plane.uv = uvs;
		//_plane.normals = normals;
        _plane.RecalculateNormals();

        return _plane;
	}
	
	protected static Mesh _plane; 
}
